<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\api\library\ExceptionHandle;
use app\admin\model\Third;
use app\admin\model\SurprisedGoods;
use app\common\model\User;
use think\Config;
use think\Db;
/**
 *  微信支付
 *
 *  Author:  YSX
    Date:    2022-7-4
 */
class Wxpay extends Api
{
    protected $noNeedLogin = ['notify'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }
	/**
	 * 微信统一支付
	 */
	public function pay()
	{
	    $order_no = $this->request->post('order_no');
	    if (!$order_no) {
	        $this->error('订单号不能为空');
	    }
	    $order = Db::name('surprised_order')->where('order_no', $order_no)->find();
	    if (!$order) {
	        $this->error('订单不存在');
	    }
	    $user = User::where(['id' => $this->auth->id])->find();
	    if ($user['id'] != $this->auth->id) {
	        $this->error('当前订单不属于当前用户');
	    }
	    $openid = Third::where(['user_id' => $user['id']])->value('openid');
	    if(!$openid) {
	        $this->error('openid 为空不能进行支付');
	    }
	    if ($order['pay_status'] == 2) {
	        $this->error('订单已支付');
	    }

		//通知地址  确保外网能正常访问
		$notify_url = 'https://'.$_SERVER['HTTP_HOST'].'/index.php/api/WxPay/notify';
		//统一下单接口
		$ExceptionHandle = new ExceptionHandle();
		$unifiedorder = $ExceptionHandle->unifiedorder($openid,$order_no,$order['pay_money'],$notify_url,'惊喜商品订单');
		if ($unifiedorder['result_code'] == 'FAIL') {
			$this->error($unifiedorder['err_code_des']);
		}
		$wx_config = Config::get('wx_config');
		$parameters = array(
			'appId' => $wx_config['appid'], //小程序 ID
			'timeStamp' => '' . time() . '', //时间戳
			'nonceStr' => $ExceptionHandle->createNoncestr(), //随机串
			'package' => 'prepay_id=' . $unifiedorder['prepay_id'], //数据包
			'signType' => 'MD5'//签名方式
		);
		//签名
		$parameters['paySign'] = $ExceptionHandle->getWxSign($parameters,$wx_config['mch_key']);
		$parameters['order_no'] = $order_no;
		$this->success('获取成功', $parameters);
	}
	/**
	 * 支付回调
	 */
	public  function notify()
	{
	    $xml = file_get_contents("php://input");
	    // file_put_contents('wx.txt', $xml);
	    $objectxml = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);//将文件转换成 对象
	    $xmljson= json_encode($objectxml);//将对象转换个JSON
	    $xmlarray=json_decode($xmljson,true);//将json转换成数组
	    $out_trade_no = $xmlarray['out_trade_no'];
	    // $openid = $xmlarray['openid'];
		// $out_trade_no = '202207061431569185131679';
	    $this->NotifyUrlStatus($out_trade_no);
	    $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
	    echo $str;
		// $out_trade_no = '202205261650200000391081';
		// ExceptionHandle::NotifyUrlStatus($out_trade_no);
	}
	public function NotifyUrlStatus($order_no,$openid = '')
	{
	    // $order_no = '202205261650200000391081';
		$order =Db::name('surprised_order')->where(['order_no' => $order_no])->find();
		$orderGoods = Db::name('surprised_order_goods')->where(['order_id' => $order['id']])->select();
		$update = [
			'status' => 2,
			'pay_status' => 2,
			'pay_time' => time(),
		];
		$result = Db::name('surprised_order')->where(['id' => $order['id']])->update($update);
		// $result = true;
		if($result){
			foreach($orderGoods as $key => $value){
				//把商品已售数量加1
				SurprisedGoods::where(['id' => $value['goods_id']])->setInc('sales',$value['number']);
				SurprisedGoods::where(['id' => $value['goods_id']])->setDec('stock',$value['number']);
			}
			//增加支付记录
			$p_data['user_id'] = $order['member_id'];
			$p_data['order_id'] = $order['id'];
			$p_data['mobile'] = Db::name('member_address')->where(['id' => $order['address_id']])->value('mobile');
			$p_data['money'] = $order['pay_money'];
			$p_data['content'] = '惊喜订单支付';
			$p_data['type'] = 1;
			$p_data['add_time'] = $_SERVER['REQUEST_TIME'];
			$p_data['add_date'] = date("Y-m-d H:i:s",$p_data['add_time']);
			$res = Db::name('pay_log')->insert($p_data);
			if($res){
				return true;
			}else{
				return false;
			}
		}
	}
}
